<template>
  <div class="main">
    <div class="minmap-container">
      <button @click="open">打开</button>
      <button @click="save">保存</button>
      <MindMap ref="mindMapRef" />
    </div>
    
    <a-drawer 
      v-model:open="showMarkdown" 
      :title="drawerTitle" 
      placement="right" 
      size="large" 
      @close="closeMdEditor"
      :bodyStyle="{padding: '10px'}"
      :destroyOnClose="true"
    >
      <MarkdownEditor 
        ref="markdownRef"
        :defaultValue="defaultMdText"
      />
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Base64 } from 'js-base64'
import * as store from "./store/store.js"
import MindMap from './components/MindMap/index.vue'
import MarkdownEditor from './components/MarkdownEditor/index.vue'

const mindMapRef = ref()
const markdownRef = ref()
const defaultMdText = ref("")
const showMarkdown = ref(false)
const drawerTitle = ref("")

onMounted(() => {
  document.addEventListener("keydown", e => {
    console.log(e.key)
    if (e.key === "`") {
      openMdEditor()
      e.preventDefault()
    }
  });
})

const openMdEditor = () => {
  const mindMap = mindMapRef.value;
  const mdEditor = markdownRef.value;
  const activeNode = mindMap.getActiveNode();
  if (activeNode) {
    mindMap.unregisterShortcuts()
    drawerTitle.value = activeNode ? activeNode.nodeData.data.text : ""
    const md = store.getCacheMarkdown(activeNode.uid)
    if(md){
      defaultMdText.value = md
    }
    showMarkdown.value = true
  }
}

const closeMdEditor = () => {
  const mindMap = mindMapRef.value;
  const mdEditor = markdownRef.value;
  mindMap.registerShortcuts()
  const node = mindMap.getActiveNode();
  const md = mdEditor.getCacheValue()
  if(md && md.trim()){
    store.cacheMarkdown(node.uid, md)
    node.setNote("点击查看")
  }
  mdEditor.clearCache()
}

const getAllData = () => {
  const mindData = mindMapRef.value.getData();
  const uids = store.getCacheNodeUids()
  const markdowData = uids.reduce((obj, uid) => {
    const md = store.getCacheMarkdown(uid)
    obj[uid] = Base64.encode(md)
    return obj
  }, {})
  return {
    mindMap: mindData,
    markdown: markdowData
  }
}

const setAllData = (allData) => {
  store.clearAll()
  mindMapRef.value.setData(allData.mindMap)
  Object.keys(allData.markdown).forEach(key => {
    const md = Base64.decode(allData.markdown[key])
    store.cacheMarkdown(key, md)
  })
}

const save = async () => {
  const fileHandle = await window.showSaveFilePicker({
    types: [
      {
        description: '',
        accept: { 'application/json': ['.json'] }
      }
    ],
  })
  const allData = getAllData();
  const content = JSON.stringify(allData);
  const writable = await fileHandle.createWritable()
  await writable.write(content)
  await writable.close()
}

const open = async () => {
  let [fileHandle] = await window.showOpenFilePicker({
    types: [
      {
        description: '',
        accept: {
          'application/json': ['.json']
        }
      }
    ],
    excludeAcceptAllOption: true,
    multiple: false
  })
  let file = await fileHandle.getFile()
  let fileReader = new FileReader()
  fileReader.onload = async e => {
    const content = e.target.result
    setAllData(JSON.parse(content))
  }
  fileReader.readAsText(file)
}
</script>

<style scoped>
.main {
  display: flex;
  flex-direction: row;
  max-height: 100vh;
  max-width: 100vw;
  overflow: hidden;
}

.minmap-container {
  width: 100%;
}

.hide-md-item {
  visibility: hidden;
  width: 0px;
}

.show-md-item {
  visibility: visible;
  width: 40vw;
}
</style>
